<script setup lang="ts">
import * as monaco from 'monaco-editor';
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker';
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker';
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker';

import { useTheme } from '@season-designable/vue';

const props = defineProps(['value']);

const emits = defineEmits(['onChange']);

const element = ref<HTMLElement | null>(null);

const theme = useTheme();

window.MonacoEnvironment = {
  getWorker(_: string, label: string) {
    if (label === 'json') {
      return new jsonWorker();
    }
    if (label === 'css' || label === 'scss' || label === 'less') {
      return new cssWorker();
    }
    if (label === 'html' || label === 'handlebars' || label === 'razor') {
      return new htmlWorker();
    }
    if (label === 'typescript' || label === 'javascript') {
      return new tsWorker();
    }
    return new editorWorker();
  },
};

onMounted(async () => {
  await nextTick();

  if (element.value) {
    const editor = monaco.editor.create(element.value, {
      value: props.value,
      language: 'json', // 语言类型
      glyphMargin: true,
      tabSize: 2,
      smoothScrolling: true,
      scrollbar: {
        verticalScrollbarSize: 5,
        horizontalScrollbarSize: 5,
        alwaysConsumeMouseWheel: false,
      },
      theme: theme === 'dark' ? 'monokai' : 'chrome-devtools', // 主题
    });

    editor.onDidChangeModelContent(() => {
      emits('onChange', editor.getValue());
      // console.log(editor.getValue());
    });
  }
});
</script>

<template>
  <div class="monaco-input" ref="element"></div>
</template>

<style lang="scss" scoped>
.monaco-input {
  width: 100%;
  height: 100%;
}
</style>
